<template>
  <div class="employees-container">
    <div class="app-container">
      <pageTool>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployees">新增员工</el-button>
        </template>
      </pageTool>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop:'timeOfEntry',order:'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}

            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ translateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹窗 -->
      <el-dialog :visible.sync="showForm" title="新增或编辑" @close="hClose">
        <addEmployeesForm ref="formRef" @success="hSuccess" @close="hClose" @jumpPage="hjumpPage" />
      </el-dialog>
      <!-- 分配角色弹窗 -->
      <el-dialog v-if="showRole" :visible.sync="showRole" title="分配角色">
        <assignRole :employee-id="curEmployeeId" @close="hCloseRole" />
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { getEployeesList, delEmployee } from '@/api/employee'
import employeesEnum from '@/constant/employees.js'
import addEmployeesForm from '@/views/emloyees/addEmployees.vue'
import assignRole from '@/views/emloyees/assignRole.vue'

import dayjs from 'dayjs'
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   // 转换成{1：正式}
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addEmployeesForm,
    assignRole

  },
  data() {
    return {
      page: 1,
      size: 5,
      total: 0,
      list: [],
      showForm: false,
      showRole: false,
      curEmployeeId: ''

    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {

    // 关闭分配角色弹窗
    hCloseRole() {
      this.showRole = false
    },
    // 弹出分配角色弹窗
    hAssignRole(id) {
      this.showRole = true
      this.curEmployeeId = id
    },
    // 用dayjs格式化时间
    translateTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 添加员工
    addEmployees() {
      this.showForm = true
    },
    // 获取员工列表渲染页面
    async loadEmployeesList() {
      try {
        const res = await getEployeesList(this.page, this.size)
        // console.log(res, 'loadEmployeesList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    formOfEmploymentFormat(val) {
      // hireType===>{1:正式，2:非正式}
      return hireType[val] ? hireType[val] : '未知'
      // try {
      //   return employeesEnum.hireType.find(item => item.id === val).value
      // } catch {
      //   return '未知'
      // }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.size = val
      this.page = 1
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },
    // 删除
    async doDelete(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 刷新列表
        this.loadEmployeesList()
      // 保存数据
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    // 导出生成excel
    async handleDownload() {
      // 获取数据
      const res = await getEployeesList(this.page, this.total)
      console.log(res, 'handleDownload')
      const list = res.data.rows
      // 英文转中文
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enTranslateZh = (list) => {
        // 获取英文头部,转成中文头部
        const header = Object.keys(list[0]).map(enKey => {
          return map[enKey]
        })
        console.log(header)
        // 转化员工聘用形式数据
        const data = list.map(item => {
          item['formOfEmployment'] = hireType[item['formOfEmployment']] || '未知'
          item['correctionTime'] = item['correctionTime'] || '-'
          return Object.values(item)
        })
        return { header, data }
      }
      const { header, data } = enTranslateZh(list)
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = [[1, '第一条数据', 'summer', '222', '2022-07-18'], [2, '第二条数据', 'summer1', '333', '2022-07-18']]

        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header,
          data,
          // header: ['姓名', '工资'], // 表头 必填
          // data: [
          //   ['刘备', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          // header: tHeader,
          // data: filterVal,
          filename: 'excel-employees-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
          // filename: this.filename, // 文件名
          // autoWidth: this.autoWidth, // 宽度是否自适应
          // bookType: this.bookType // 生成文件类型
        })
      })
    },
    hDel(id) {
      // this.$confirm('确认删除吗', '提示', {
      //   confirmButtonText: '确认',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      this.doDelete(id)
      // }).catch(() => {})
    },
    hjumpPage() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
    },
    hSuccess() {
      this.loadEmployeesList()
      this.showForm = false
    },
    hClose() {
      this.showForm = false
      this.$refs.formRef.resetForm()
    }
  }
}
</script>

<style>

</style>
